/**
 * Created by george on 16/4/9.
 */
var argv = require('yargs').argv;
var IS_DEV = (argv.dev !== undefined);

console.log(IS_DEV ? "DEVELOP_MODE" : "PRODUCTION_MODE");

var gulp = require('gulp'),
  less = require('gulp-less'),
  postcss = require('gulp-postcss'),
  notify = require('gulp-notify'),
  plumber = require('gulp-plumber'),
  gutil = require("gulp-util"),
  // autoprefixer = require("gulp-autoprefixer"),
  concat = require("gulp-concat"),
  rev = require("gulp-rev-append"),
  gulpif = require("gulp-if"),
  webpack = require("webpack"),
  header = require("gulp-header"),
  // rename = require("gulp-rename"),
  revdist = require("gulp-rev"),
  clean = require("gulp-clean"),
  collector = require("gulp-rev-collector"),
  revReplace = require("gulp-rev-replace"),
  runSequence = require("run-sequence");

// package info for common header
var pkg = require('./package.json');
var banner = ['/**',
  ' * <%= pkg.name %> - <%= pkg.description %>',
  ' * @Version v<%= pkg.version %>',
  ' * @Released At <%= new Date().Format("yyyy/MM/dd hh:mm") %>',
  ' * @Author George',
  // ' * @Link <%= pkg.homepage %>',
  // ' * @License <%= pkg.license %>',
  ' */',
  ''].join('\n');

// CSS打包
gulp.task('runLess', function () {
  return gulp.src(['src/entry.less'])
    .pipe(revdist())
    .pipe(concat('asset.css'))
    .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
    .pipe(less())
    // .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(gulpif(!IS_DEV, postcss([require('autoprefixer')({browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4']}), require('cssnano')({compatibility: 'ie7'})])))
    // .pipe(gulpif(!IS_DEV, cssmin({compatibility: 'ie7'})))
    .pipe(header(banner, {pkg: pkg}))
    .pipe(gulpif(!IS_DEV,revdist()))
    .pipe(gulp.dest('dist/css'))
    .pipe(gulpif(!IS_DEV,revdist.manifest()))
    .pipe(gulpif(!IS_DEV,gulp.dest('dist/css/rev')));
  // .pipe(notify({message: 'Styles task complete'}));
});

// JS处理
gulp.task('compileJs', function (cb) {
  runSequence("revJs", cb); //"cleanJsFiles"
});

// JS版本控制
gulp.task('revJs', function () {
  return gulp.src(['dist/js/*.js'])
      .pipe(header(banner, {pkg: pkg}))
      .pipe(revdist())
      .pipe(gulp.dest('dist/js'))
      .pipe(revdist.manifest())
      .pipe(gulp.dest('dist/js/rev'));
});

// 静态页面引用引用版本控制
gulp.task('revBundle', function () {
  //if (IS_DEV) {
  //  return gulp.src('./*.html')
  //      .pipe(rev())
  //      .pipe(gulp.dest('./'));
  //} else {
    return gulp.src(['dist/**/rev/*.json', './*.html'])
        .pipe(gulpif(!IS_DEV,collector({
          replaceReved: true
        })))
        .pipe(rev())
        .pipe(gulp.dest('./'));
  //}
});

gulp.task('devRevBundle', function () {
    return gulp.src('./*.html')
        .pipe(rev())
        .pipe(gulp.dest('./'));
});

// depreciated
gulp.task('revReplace', function () {
  var manifest = gulp.src('./dist/js/rev/rev-manifest.json');
  return gulp.src('./index.html')
      .pipe(revReplace({manifest: manifest}))
      .pipe(gulp.dest('./'));
});

// WEBPACK打包
var wbConfig = IS_DEV ? "./webpack.dev.config.js" : "./webpack.rel.config.js";
var webpackConfig = require(wbConfig);

gulp.task("webpack", function (callback) {
  var myConfig = Object.create(webpackConfig);
  // run webpack
  webpack(
    // configuration
    myConfig
    , function (err, stats) {
      if (err) {
        throw new gutil.PluginError("webpack", err);
      }
      gutil.log("[webpack]", stats.toString({
        // output options
      }));
      callback();
    });
});

// clean任务
gulp.task('clean', function () {
  return gulp.src(['dist/css', 'dist/js'], {read: false})
    .pipe(clean());
});

// clean CSS任务
gulp.task('cleanCss', function () {
  return gulp.src(['dist/css'], {read: false})
    .pipe(clean());
});

// clean JS任务
gulp.task('cleanJs', function () {
  return gulp.src(['dist/js'], {read: false})
    .pipe(clean());
});

// clean JS files任务
gulp.task('cleanJsFiles', function () {
  return gulp.src(['dist/js/*.js'], {read: false})
      .pipe(clean());
});

// 监视任务
gulp.task('watch', function () {
  gulp.watch(['src/**/*.less', 'src/**/**/*.less'], ['devCompileCss']);
  gulp.watch(['src/**/*.js', 'src/**/**/*.js'], ['devCompile']);
});

gulp.task('compileCss', function (cb) {
  runSequence('cleanCss', 'runLess', 'revBundle', cb);
});

// 打包任务
gulp.task('compile', function (cb) {
  runSequence('clean', 'runLess', 'webpack', 'compileJs', 'revBundle', cb);
});

// 打包任务
gulp.task('devCompile', function (cb) {
  runSequence('webpack', 'devRevBundle', cb);
});
gulp.task('devCompileCss', function (cb) {
  runSequence('runLess', 'devRevBundle', cb);
});

// Format date
Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "h+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    "S": this.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(String(o[k]).length)));
    }
  }
  return fmt;
};
